<template>
	<div class="zh-system-message">
		<nav-header></nav-header>
		<div class="zh-charts" v-loading="loading.status" :element-loading-text="loading.txt">
			<div class="zh-charts-tip">
				<div>运行时间：{{ topInfo.runTime }}</div>
				<div>内存总量：{{ topInfo.memSum }}</div>
				<div>磁盘总量：{{ topInfo.romSum }}</div>
				<div>激活时间：{{ topInfo.enaTime }}</div>
			</div>
			<div class="zh-charts-tip">

				<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="70px" class="cdkey-rorm">
					<el-form-item label="序列号:" prop="" class="code-form-item1">{{ topInfo.serNum }}</el-form-item>
					<el-form-item label="注册码:" prop="passnum" class="code-form-item2">
						<el-input v-model.trim="ruleForm.passnum" placeholder="将获取的激活码粘贴到此处"></el-input>
					</el-form-item>
					<el-form-item label-width="20px" class="send-item">
						<el-button type="primary" @click="submitForm('ruleForm')">激活</el-button>
					</el-form-item>
				</el-form>
			</div>
			<ve-line :data="chartData" :yAxis="yAxis" :tooltip="tooltipOption" :settings="chartSet" class="ve-line"></ve-line>
			<div class="clear">
				<div class="charts-area">
					<ve-pie :data="cpuData" :settings="chartSetting"></ve-pie>
				</div>
				<div class="charts-area">
					<ve-pie :data="memoryData" :settings="chartSetting"></ve-pie>
				</div>
			</div>
		</div>
	</div>
</template>
<script>
var max = 100000000000000000;
var max_memory = 0;
export default {
	data() {
		this.chartSet = {
			metrics: ['内存占用', 'CPU占用（用户）', 'CPU占用（系统）', '磁盘读取', '磁盘写入', '网络上传', '网络下载'],
			dimension: ['日期'],
		},
			this.chartSetting = {
				radius: 120,
				offsetY: 200,
				dimension: '别名',
				metrics: '占用率',
			}
		return {
			loading: {
				status: false,
				txt: '获取数据...',
			},
			ruleForm: {
				uuid: '',
				passnum: ''
			},
			rules: {
				passnum: [
					{
						required: true,
						message: '请输入注册码',
						trigger: 'blur'
					}
				]
			},
			bootTime: null,
			topInfo: {
				runTime: '稍等片刻...',
				memSum: '稍等片刻...',
				romSum: '稍等片刻...',
				serNum: '0D2033BC-7D17-5FF6-4772-227774AE4EE1', // 序列号
				enaTime: '永久' // 激活时间
			},
			systemInfoTimeOut: {},
			runInfoTimeOut: {},
			yAxis: { show: false },
			infoData: [],
			chartData: {
				columns: ['日期', '内存占用', 'CPU占用（用户）', 'CPU占用（系统）', '磁盘读取', '磁盘写入', '网络上传', '网络下载'],
				rows: []
			},
			cpuData: {
				columns: ['别名', '占用率'],
				rows: []
			},
			memoryData: {
				columns: ['别名', '占用率'],
				rows: []
			},
			firstTime: true,
			tooltipOption: {
				trigger: 'axis',
				formatter: function (param) {
					var html = param[0].data[0] + '<br>'
					for (var i = 0; i <= param.length - 1; i++) {
						html += param[i].marker + param[i].seriesName + ' : ';

						switch (i) {
							case 0:
								html += hfsize((param[i].data[1] * max_memory) / max) + '<br>';
								break;
							case 1:
								html += (param[i].data[1] * 100 / max) + '%<br>';
								break;
							case 2:
								html += (param[i].data[1] * 100) / max + '%<br>';
								break;
							case 3:
								html += hfsize((param[i].data[1] * 1048576 * 300) / max) + '/S<br>';
								break;
							case 4:
								html += hfsize((param[i].data[1] * 1048576 * 100) / max) + '/S<br>';
								break;
							case 5:
								html += hfsize((param[i].data[1] * 1048576 * 1000) / max) + '/S<br>';
								break;
							case 6:
								html += hfsize((param[i].data[1] * 1048576 * 100) / max) + '/S<br>';
								break;
						}
					}
					return html;
				}
			}
		}
	},
	created() {
		this.getSerNumber()
		this.getSertusCode()
	},
	mounted() {
		if (this.firstTime) {
			this.loading.status = true;
			this.getSystemInfo();
		}

		this.systemInfoTimeOut = setInterval(() => {
			this.getSystemInfo();
		}, 5 * 1000)

		//运行时间
		this.runInfoTimeOut = setInterval(() => {
			if (!is_empty(this.bootTime)) {
				this.formatRunTime();
			}

		}, 1000)
	},
	methods: {
		submitForm(formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					this.send();
				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		send() {
			let success = res => {
				this.$message.success('激活成功');
				this.getSerNumber();
				this.ruleForm.passnum = '';
			};
			let fail = res => {
				this.$message.error('激活失败');
			};
			this.$ajax({
				url: '/index/checkpass/auto_pass',
				method: 'post',
				data: this.ruleForm,
				func: {
					success: success,
					fail: fail
				}
			});
		},
		getSerNumber() { // 获取激活时间
			let success = res => {
				let data = res.data
				this.topInfo.enaTime = data.time == data.last_time ? '永久' : data.time + ' 至 ' + data.last_time
			}
			this.$ajax.get('/api/login/getRegisterInfo', { params: {}, func: { success } })
		},
		getSertusCode() { // 获取序列号
			let success = res => {
				this.topInfo.serNum = res.data
				this.ruleForm.uuid = res.data
			}
			this.$ajax.get('/index/checkpass/get_uuid2', { params: {}, func: { success } })
		},
		getSystemInfo() {
			let success = (data => {
				if (this.firstTime) {
					this.firstTime = false;
					this.loading.status = false;
				}
				var info = data.data;
				max_memory = info[0];
				var b_time = timestampToTime(info[3]).substr(10, 9);
				var mem_use = (info[1] * max) / max_memory;
				var cpu_user = (info[7] * max) / 100;
				var cpu_sys = (info[8] * max) / 100;
				var rom_read = (info[10] * max) / (1048576 * 300);
				var rom_write = (info[11] * max) / (1048576 * 100);
				var net_upload = (info[13] * max) / (1048576 * 1000);
				var net_download = (info[12] * max) / (1048576 * 100);

				this.chartData.rows.push({ '日期': b_time, '内存占用': mem_use, 'CPU占用（用户）': cpu_user, 'CPU占用（系统）': cpu_sys, '磁盘读取': rom_read, '磁盘写入': rom_write, '网络上传': net_upload, '网络下载': net_download });
				if (this.chartData.rows.length > 60) {
					this.chartData.rows.splice(0, 1);
				}
				this.topInfo.memSum = hfsize(info[0]);
				this.topInfo.romSum = hfsize(info[5]) + '（已使用' + info[6] + ')'
				this.cpuData.rows = [
					{ '别名': 'CPU空闲', '占用率': info[9] },
					{ '别名': '用户占用', '占用率': info[7] },
					{ '别名': '系统占用', '占用率': info[8] },
				]
				this.memoryData.rows = [
					{ '别名': '内存空闲', '占用率': info[14] },
					{ '别名': '实际占用', '占用率': info[15] },
					{ '别名': '内存缓冲', '占用率': info[16] },
				]

				if (this.chartData.rows.length === 1) {
					this.bootTime = info[3] - info[2];
					this.formatRunTime();
				}

			})
			let fail = (data => {
				this.$message.error(data.msg);
				if (this.firstTime) {
					this.firstTime = false;
					this.loading.status = false;
				}
			})
			this.$ajax.get('api/system/system_info', { params: {}, func: { success: success, fail: fail } })
		},
		formatRunTime() {
			var day = Math.floor(this.bootTime / (24 * 60 * 60));
			var hour = Math.floor((this.bootTime - (24 * 60 * 60) * day) / (60 * 60));
			var minute = Math.floor((this.bootTime - (24 * 60 * 60) * day - (60 * 60) * hour) / 60);
			minute = minute < 10 ? '0' + minute : minute;
			var second = (this.bootTime % 60) < 10 ? '0' + this.bootTime % 60 : this.bootTime % 60;
			this.topInfo.runTime = (day > 0 ? (day + ' 天 ') : '') + (hour > 0 ? (hour + ' 小时 ') : '') +
				minute + ' 分钟 ' +
				second + ' 秒'
			this.bootTime++;
		},
	},
	//离开页面之前
	beforeRouteLeave(to, from, next) {
		clearInterval(this.systemInfoTimeOut)
		clearInterval(this.runInfoTimeOut)
	},
	beforeDestroy() {
		clearInterval(this.systemInfoTimeOut)
		clearInterval(this.runInfoTimeOut)
	}
}
</script>
<style lang="scss">
.zh-system-message {
	.zh-charts {
		.charts-area {
			float: left;
			width: 50%;
		}

		.zh-charts-tip {
			margin: 0 0 40px;

			>div {
				display: inline-block;
				margin-right: 50px;
			}

			.cdkey-rorm {
				display: flex;

				.code-form-item1 {
					width: 400px;
				}

				.code-form-item2 {
					width: 500px;
				}
			}
		}

		.ve-line {
			padding-top: 20px;
			margin-bottom: 40px;
			border: 1px solid #e6e6e6;

			canvas {
				margin-left: -4% !important;
			}
		}
	}
}
</style>